package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.DateFormatUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.WQbdFlightTest;
import com.ccp.dev.qbdms.service.WQbdFlightTestService;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.service.DictionaryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 飞行成功统计管理 信息操作处理控制器
 *
 * @author hw
 * @date 2020-07-20
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "飞行成功统计管理")
@RequestMapping("/qbdms/flightSuccessStatistics")
public class FlightSuccessStatisticsController extends SysBaseController {
    @Resource
    private WQbdFlightTestService wQbdFlightTestService;
    @Resource
    private DictionaryService dictionaryService;

    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/flightSuccessStatisticsCharts")
    @Action(description = "跳转飞行成功统计页面", exectype = "页面跳转日志")
    public String viewStatistics(HttpServletRequest request, ModelMap modelMap){

        QueryFilter queryFilter = new QueryFilter(request, false);
        String beginTestdate = DateFormatUtil.format(new Date(),"yyyy")+"-01";
        String endTestdate = DateFormatUtil.format(new Date(),"yyyy-MM");
        queryFilter.addFilter("beginTestdate", beginTestdate);
        queryFilter.addFilter("endTestdate",endTestdate);

        //获取所有飞行结果
        String flightResult = wQbdFlightTestService.queryAllFlightResult();
        String[] flightResultArr  = null;
        if(BeanUtils.isNotEmpty(flightResult)){
            flightResultArr = flightResult.split(",");
        }

        //获取所有型号研制阶段
        String modelDevelopPhase = wQbdFlightTestService.queryModelDevelopPhase();
        String[] modelDevelopPhaseArr  = null;
        if(BeanUtils.isNotEmpty(modelDevelopPhase)){
            modelDevelopPhaseArr = modelDevelopPhase.split(",");
        }

        List dataList = new ArrayList();

        String filghtResultToStr = "[";

        if(BeanUtils.isNotEmpty(flightResultArr) && flightResultArr.length > 0){
            for(int i=0;i<flightResultArr.length;i++){
                filghtResultToStr = filghtResultToStr + "'"+flightResultArr[i]+"'"+',';
                //做相应数据的查询拼接
                String dataResult = "[";
                for(int j=0;j<modelDevelopPhaseArr.length;j++){
                    queryFilter.addFilter("flightResult",flightResultArr[i]);
                    queryFilter.addFilter("modelDevelopPhase",modelDevelopPhaseArr[j]);
                    ZhiLiangConst.addQueryFilter(queryFilter);
                    Integer result = wQbdFlightTestService.getFlightResultCount(queryFilter);
                    dataResult = dataResult + result + ',';
                }
                dataResult = dataResult.substring(0,dataResult.length()-1) + "]";
                dataList.add(dataResult);
            }
        }else{
            filghtResultToStr = filghtResultToStr + ',';
        }

        String maxScret = wQbdFlightTestService.getFlightResultMaxSecret(queryFilter);
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);


        filghtResultToStr = filghtResultToStr.substring(0,filghtResultToStr.length()-1) + "]";


        String modelDevelopPhaseToStr = "[";
        if(BeanUtils.isNotEmpty(modelDevelopPhaseArr) && modelDevelopPhaseArr.length > 0){
            for(int i=0;i<modelDevelopPhaseArr.length;i++){
                modelDevelopPhaseToStr = modelDevelopPhaseToStr + "'"+modelDevelopPhaseArr[i]+"'"+',';
            }
        }else{
            modelDevelopPhaseToStr = modelDevelopPhaseToStr + ',';
        }
        modelDevelopPhaseToStr = modelDevelopPhaseToStr.substring(0,modelDevelopPhaseToStr.length()-1) + "]";

        String jsonList = JSON.toJSONString(dataList);

        /**--------------------------------折线图-----------------------------------------**/
        List<String> yearList = new ArrayList();

        String nowYear = DateFormatUtil.getNowByString("yyyy");
        int firstOldYear = Integer.parseInt(nowYear) - 1;
        int secondOldYear = firstOldYear - 1;
        yearList.add(secondOldYear + "");
        yearList.add(firstOldYear + "");
        yearList.add(nowYear);

        List dataListZhe = new ArrayList();

        QueryFilter queryFilterSuc = new QueryFilter(request,false);
        queryFilterSuc.addFilter("array",yearList.toArray());
        ZhiLiangConst.addQueryFilter(queryFilterSuc);
        String sucMaxSecret = wQbdFlightTestService.getSuccessFlightResultMaxSecret(queryFilterSuc);

        for (Dictionary dictionary : dicList) {
            if (dictionary.getItemValue().equals(maxScret)) {
                // 柱状图密级显示名称
                maxScret = dictionary.getItemName();
            }
            if (dictionary.getItemValue().equals(sucMaxSecret)) {
                // 折线图密级显示名称
                sucMaxSecret = dictionary.getItemName();
            }
        }

        if(BeanUtils.isNotEmpty(modelDevelopPhaseArr) && modelDevelopPhaseArr.length > 0){
            for(int i=0;i<modelDevelopPhaseArr.length;i++){
                String dataResult = "[";
                for(int j=0;j<yearList.size();j++){
                    QueryFilter queryFilterZhe = new QueryFilter(request,false);

                    queryFilterZhe.addFilter("name",modelDevelopPhaseArr[i]);
                    queryFilterZhe.addFilter("year",yearList.get(j));
                    ZhiLiangConst.addQueryFilter(queryFilterZhe);

                    Integer allFlight = wQbdFlightTestService.querySuccessFlight(queryFilterZhe);

                    queryFilterZhe.addFilter("flightresult","true");
                    Integer successFlight = wQbdFlightTestService.querySuccessFlight(queryFilterZhe);
                    //计算百分数
                    double baifenshu;
                    if(allFlight != 0){
                        DecimalFormat df=new DecimalFormat(".00");

                        baifenshu = new BigDecimal((float)successFlight/allFlight).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                        baifenshu = queryNumber(baifenshu);
                    }else{
                        baifenshu = 0;
                    }
                    double lastResult = baifenshu/100;
//                    lastResult = queryNumber(lastResult);

                    dataResult = dataResult + lastResult + ',';

                }
                dataResult = dataResult.substring(0,dataResult.length()-1) + "]";
                dataListZhe.add(dataResult);
            }
        }

        modelMap.put("flightResult",filghtResultToStr);
        modelMap.put("modelDevelopPhase",modelDevelopPhaseToStr);
        modelMap.put("dataList", jsonList);
        modelMap.put("beginTestdate", beginTestdate);
        modelMap.put("endTestdate", endTestdate);







        modelMap.put("maxScret",maxScret);
        modelMap.put("sucMaxSecret",sucMaxSecret);

        modelMap.put("dataListZhe",JSON.toJSONString(dataListZhe));
        modelMap.put("modelDevelopPhaseZhe",modelDevelopPhaseToStr);
        modelMap.put("years",JSON.toJSONString(yearList));

        return "flightSuccessStatistics/flightSuccessStatisticsCharts";
    }

    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/showList")
    @Action(description = "跳转查询明细页面", exectype = "页面跳转日志")
    public String viewShowList(HttpServletRequest request, ModelMap modelMap){
        String name = RequestUtil.getString(request,"name");
        String seriesName = RequestUtil.getString(request,"seriesName");
        String beginDate = RequestUtil.getString(request,"beginDate");
        String endDate = RequestUtil.getString(request,"endDate");
        modelMap.put("name",name);
        modelMap.put("seriesName",seriesName);
        modelMap.put("seriesName",seriesName);
        modelMap.put("beginDate",beginDate);
        modelMap.put("endDate",endDate);
        return "flightSuccessStatistics/showList";
    }

    @RequestMapping("/showList")
    @ResponseBody
    @Action(description = "查询数据信息", exectype = "查询日志")
    public Object showList(HttpServletRequest request, ModelMap modelMap) throws IllegalAccessException{
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照试验时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "f_testdate");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        queryFilter.addFilter("name",RequestUtil.getString(request,"name"));
        queryFilter.addFilter("seriesName",RequestUtil.getString(request,"seriesName"));
        queryFilter.addFilter("beginDate",RequestUtil.getString(request,"beginDate"));
        queryFilter.addFilter("endDate",RequestUtil.getString(request,"endDate"));
        ZhiLiangConst.addQueryFilter(queryFilter);
        // 分页数据
        List<WQbdFlightTest> pageDatas = wQbdFlightTestService.queryShowList(queryFilter);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }

    @RequestMapping("/getChartData")
    @ResponseBody
    @Action(description = "查询数据信息", exectype = "查询日志")
    public Object getChartData(HttpServletRequest request, ModelMap modelMap) throws Exception{

        QueryFilter queryFilter = new QueryFilter(request, false);
        String beginTestdate = "";
        String endTestdate = "";
        if(StringUtil.isNotEmpty(RequestUtil.getString(request,"beginTestdate")) && StringUtil.isNotEmpty(RequestUtil.getString(request,"endTestdate"))){
            beginTestdate = RequestUtil.getString(request,"beginTestdate");
            queryFilter.addFilter("beginTestdate",RequestUtil.getString(request,"beginTestdate"));
            endTestdate = RequestUtil.getString(request,"endTestdate");
            queryFilter.addFilter("endTestdate",RequestUtil.getString(request,"endTestdate"));
        }else{
            beginTestdate = DateFormatUtil.format(new Date(),"yyyy")+"-01";
            endTestdate = DateFormatUtil.format(new Date(),"yyyy-MM");
            queryFilter.addFilter("beginTestdate", beginTestdate);
            queryFilter.addFilter("endTestdate",endTestdate);
        }

        //获取所有飞行结果
        String flightResult = wQbdFlightTestService.queryAllFlightResult();
        String[] flightResultArr  = null;
        if(BeanUtils.isNotEmpty(flightResult)){
            flightResultArr = flightResult.split(",");
        }

        //获取所有型号研制阶段
        String modelDevelopPhase = wQbdFlightTestService.queryModelDevelopPhase();
        String[] modelDevelopPhaseArr  = null;
        if(BeanUtils.isNotEmpty(modelDevelopPhase)){
            modelDevelopPhaseArr = modelDevelopPhase.split(",");
        }

        List dataList = new ArrayList();

        String filghtResultToStr = "[";

        if(BeanUtils.isNotEmpty(flightResultArr) && flightResultArr.length > 0){
            for(int i=0;i<flightResultArr.length;i++){
                filghtResultToStr = filghtResultToStr + "'"+flightResultArr[i]+"'"+',';
                //做相应数据的查询拼接
                String dataResult = "[";
                for(int j=0;j<modelDevelopPhaseArr.length;j++){
                    queryFilter.addFilter("flightResult",flightResultArr[i]);
                    queryFilter.addFilter("modelDevelopPhase",modelDevelopPhaseArr[j]);
                    ZhiLiangConst.addQueryFilter(queryFilter);
                    Integer result = wQbdFlightTestService.getFlightResultCount(queryFilter);
                    dataResult = dataResult + result + ',';
                }
                dataResult = dataResult.substring(0,dataResult.length()-1) + "]";
                dataList.add(dataResult);
            }
        }else{
            filghtResultToStr = filghtResultToStr + ',';
        }
        filghtResultToStr = filghtResultToStr.substring(0,filghtResultToStr.length()-1) + "]";


        String modelDevelopPhaseToStr = "[";
        if(BeanUtils.isNotEmpty(modelDevelopPhaseArr) && modelDevelopPhaseArr.length > 0){
            for(int i=0;i<modelDevelopPhaseArr.length;i++){
                modelDevelopPhaseToStr = modelDevelopPhaseToStr + "'"+modelDevelopPhaseArr[i]+"'"+',';
            }
        }else{
            modelDevelopPhaseToStr = modelDevelopPhaseToStr + ',';
        }
        modelDevelopPhaseToStr = modelDevelopPhaseToStr.substring(0,modelDevelopPhaseToStr.length()-1) + "]";

        String jsonList = JSON.toJSONString(dataList);

        modelMap.put("flightResult",filghtResultToStr);
        modelMap.put("modelDevelopPhase",modelDevelopPhaseToStr);
        modelMap.put("dataList", jsonList);
        modelMap.put("beginTestdate", beginTestdate);
        modelMap.put("endTestdate", endTestdate);
        return success(modelMap);
    }

    /**
     * 转换保留两位小数
     * @param baifenshu 运算后的数据
     * @return
     */
    private Double queryNumber(double baifenshu){
        String decimalsToStr = String.valueOf(baifenshu);
        String[] decimalsToArr = decimalsToStr.split("\\.");
        if(decimalsToArr.length > 1){
            if(decimalsToArr[1].length() > 3){
                decimalsToArr[1] = decimalsToArr[1].substring(0,4);
            }else{
                if(decimalsToArr[1].length() == 1){
                    decimalsToArr[1] = decimalsToArr[1] + "000";
                }else if(decimalsToArr[1].length() == 2){
                    decimalsToArr[1] = decimalsToArr[1] + "00";
                } else if(decimalsToArr[1].length() == 3){
                    decimalsToArr[1] = decimalsToArr[1] + "0";
                }
            }
        }
        String newNumber = decimalsToArr[0] + decimalsToArr[1];
        return new Double(newNumber);
    }
}
